/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:11:00
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2019-12-16 17:02:10
 */
import { observable, action } from 'mobx';
import { message } from 'antd';
import { WeaForm } from 'comsMobx';
import { WeaTools, WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import Api from '../../apis/list';

const { Base64 } = WeaTools;

const toOptions = data => ({
  ...data,
  rows: data.rows.map(row => ({
    ...row,
    showname: row.label,
    shownameText: row.label,
  })),
});

const initState = {
  hideRight: false,
  showSearchAd: false,
  tableLoading: false,
  columns: [],
  datas: [],
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0,
  },
  selectedRowKeys: [],
  quickSeach: {},
  quickSeachValue: '',
  condition: [],
  dropDown: [],
  form: new WeaForm(),
};

export default class EmailListStore {
  name = 'inbox';
  // base
  @observable hideRight = initState.hideRight;
  @observable showSearchAd = initState.showSearchAd;
  // table
  @observable tableLoading = initState.tableLoading;
  @observable columns = initState.columns;
  @observable datas = initState.datas;
  @observable pagination = initState.pagination;
  @observable selectedRowKeys = initState.selectedRowKeys;
  // condition
  @observable quickSeach = initState.quickSeach;
  @observable quickSeachValue = initState.quickSeachValue;
  @observable condition = initState.condition;
  @observable dropDown = initState.dropDown;
  @observable form = initState.form;

  // 自动接收邮件功能store，
  @observable loadEmailsStat = ''; // 可能的值是'loading', 'success', 'fail', ''就表示还没开始收取,'finally'表示接收完成
  @observable lastReceiveTime = 0;
  @observable accountList = [];
  @observable receiveEmailsRes = []; // 每个数组元素，存的是，对于每个邮箱，向后台进行外部邮箱收取操作后台所返回的结果
  @observable receivedMailNumber = 0;
  @observable visOfRecMailsErrDeatilDia = false;

  @action
  receiveEmailInit = () => {
    this.loadEmailsStat = '';
    this.accountList = [];
    this.receiveEmailsRes = [];
    this.receivedMailNumber = 0;
  }

  @action
  autolyGetOuterEmails = async (ifReceivemail, receivemailid, success = () => {}, error = () => {}) => {
	  // 仅当ifReceivemail为true时才能自动接收邮件
    if (ifReceivemail === 'true') {
      if (receivemailid == 0 && new Date().getTime() - this.lastReceiveTime <= 1000 * 60) {
        return;
      }
      this.receiveEmailInit(); // 自动接收时，重置部分属性值
      // 若向后台获取需要接受的邮箱信息时返回status是错的则也不会向下自动接收邮件，直接报错
      let data = await Api.getReciveAccount({ receivemailid });
      const { status } = data;
      if (status !== '1') {
        message.error(getLabel(384376, '接口业务逻辑错误！'));
        return;
      }
      const { accountList } = data;
      this.accountList = accountList;
      // 仅当有需要接收的邮件时才自动接收邮件
      if (this.accountList.length > 0) {
        // 这边做的事情是让每个邮件id做外部邮箱收取操作，并把每个后台接口返回的结果都放入receiveEmailsRes变量中
        this.loadEmailsStat = 'loading';
        let ids = this.accountList.map(elem => elem.id);
        let promisesOfreceiveEmail = [];
        ids.forEach((id) => {
          promisesOfreceiveEmail.push(Api.getOuterEmails({ mailAccountId: id }));
        });
        this.receiveEmailsRes = await Promise.all(promisesOfreceiveEmail);
        // 接收完所有邮箱的所有邮件后，遍历receiveEmailsRes来检验接收是否有错，任意一个有错误那这个自动接收邮件的整个过程就是错的,此时就不执行检验逻辑了，
        // 否则就一直计算成功收到的邮件的份数
        for (let i = 0; i < this.receiveEmailsRes.length; i++) {
          if (this.receiveEmailsRes[i].status !== '1') {
            this.loadEmailsStat = 'fail';
            error();
            return;
          } else if (this.receiveEmailsRes[i].status === '1') {
            this.receivedMailNumber += Number(this.receiveEmailsRes[i].result.receivedMailNumber);
          }
        }
        this.loadEmailsStat = 'success';
        if (this.receivedMailNumber > 0) { // 如果有新邮件，刷新列表
          success();
        }
        if (receivemailid == 0) {
          this.lastReceiveTime = new Date().getTime();
        }
      }
    }
  };


  constructor(name) {
 this.name = name; 
}

  @action
  setState = (params = {}, callback) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    if (callback && typeof callback === 'function') {
      callback();
    }
    return this;
  }

  @action
  clear = () => this.setState(initState)

  @action
  getDatas = (params = {}, callback) => {
    this.tableLoading = true;
    const fn = async (p) => {
      const res = await Api.getDatas(p);
      try {
        if (res.status === '1') {
          const { tableBean: { columns, datas: _d, current, pageSize, total }, tableBean } = res;
          const datas = _d.map(d => ({
            ...d,
            content: Base64.decode(d.content),
          }));
          this.setState({ columns, datas, pagination: { current, pageSize, total } });
          typeof callback === 'function' && callback(tableBean);
        } else {
          message.error(res.msg);
        }
      } catch (e) {
        message.error(e);
      }
      this.tableLoading = false;
    };
    fn(params);
    return this;
  }

  @action
  getCondition = (params = {}) => {
    const fn = async (p) => {
      const res = await Api.getCondition(p);
      try {
        if (res.status === '1') {
          const { conditioninfo } = res;
          const { isFormInit } = this.form;
          if (isFormInit) {
            this.form = new WeaForm();
            this.condition = [];
          }
          this.condition = conditioninfo;
          this.form.initFormFields(conditioninfo);
          const { isFormInit: _isFormInit } = this.form;
          const keys = Object.keys(p);
          if (keys.length > 1 && _isFormInit) {
            const fields = {};
            keys.forEach((key) => {
              fields[key] = { value: params[key] };
            });
            this.form.updateFields(fields);
          }
        } else {
          message.error(res.msg);
        }
      } catch (e) {
        message.error(e);
      }
    };
    fn(params);
    return this;
  }

  @action
  getdropDown = (params = {}) => {
    const fn = async (p) => {
      const res = await Api.getdropDown(p);
      try {
        if (res.status === '1') {
          const { topDropDown, quickSeach } = res;
          this.dropDown = topDropDown;
          this.quickSeach = toOptions(quickSeach);
          if (!this.quickSeachValue) this.quickSeachValue = quickSeach.rows[0].key;
        } else {
          message.error(res.msg);
        }
      } catch (e) {
        message.error(e);
      }
    };
    fn(params);
    return this;
  }

  @action
  saveLayout = async (params = {}) => {
    const res = await Api.saveLayout(params);
    return res;
  }
}

// const props = {};
// const data = {
//   time: {
//     title: '你希望什么时候处理',
//     components: [{
//       type: 'SELECT_LINKAGE',
//       ...props,
//     }],
//   },
//   attention: {
//     title: 'e-mobile提醒设置',
//     label: '提醒时间',
//     components: [
//       {
//         type: 'TIMEPICKER',
//         ...props,
//       },
//       {
//         type: 'TIMEPICKER',
//         ...props,
//       },
//     ],
//   },
//   remarks: {
//     title: '备注:',
//     components: [
//       {
//         type: 'TEXTAREA',
//         ...props,
//       },
//     ],
//   },
//   others: {
//     title: '',
//     components: [
//       {
//         type: 'CHECKBOX',
//         ...props,
//       },
//       {
//         type: 'CHECKBOX',
//         ...props,
//       },
//     ],
//   },
// };
